import jwt
from functools import wraps
from django.http import JsonResponse
from django.conf import settings
from rest_framework_jwt.settings import api_settings
from .models import User, Role, UserRole, Permission


def get_user_from_token(token):
    """从JWT token中获取用户信息"""
    try:
        jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
        payload = jwt_decode_handler(token)
        user_id = payload.get('user_id')
        if user_id:
            return User.objects.get(id=user_id)
    except (jwt.InvalidTokenError, User.DoesNotExist):
        return None
    return None


def get_user_permissions(user):
    """获取用户的所有权限"""
    permissions = set()
    
    # 获取用户的所有角色
    user_roles = UserRole.objects.filter(user=user)
    
    for user_role in user_roles:
        role = user_role.role
        # 从角色的权限列表中获取权限代码
        if role.permissions:
            permissions.update(role.permissions)
    
    return list(permissions)


def require_auth(view_func):
    """需要登录验证的装饰器"""
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        # 获取Authorization header
        auth_header = request.META.get('HTTP_AUTHORIZATION', '')
        
        if not auth_header.startswith('Bearer '):
            return JsonResponse({'code': 401, 'info': '请先登录'}, status=401)
        
        token = auth_header.split(' ')[1]
        user = get_user_from_token(token)
        
        if not user:
            return JsonResponse({'code': 401, 'info': '登录已过期，请重新登录'}, status=401)
        
        # 检查用户状态
        if user.status != 0:
            return JsonResponse({'code': 403, 'info': '账户已被禁用'}, status=403)
        
        # 将用户信息添加到request中
        request.user = user
        return view_func(request, *args, **kwargs)
    
    return wrapper


def require_permission(permission_code):
    """需要特定权限的装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            # 首先验证登录
            auth_header = request.META.get('HTTP_AUTHORIZATION', '')
            
            if not auth_header.startswith('Bearer '):
                return JsonResponse({'code': 401, 'info': '请先登录'}, status=401)
            
            token = auth_header.split(' ')[1]
            user = get_user_from_token(token)
            
            if not user:
                return JsonResponse({'code': 401, 'info': '登录已过期，请重新登录'}, status=401)
            
            # 检查用户状态
            if user.status != 0:
                return JsonResponse({'code': 403, 'info': '账户已被禁用'}, status=403)
            
            # 获取用户权限
            user_permissions = get_user_permissions(user)
            
            # 检查是否有所需权限
            if permission_code not in user_permissions:
                return JsonResponse({'code': 403, 'info': '权限不足'}, status=403)
            
            # 将用户信息添加到request中
            request.user = user
            return view_func(request, *args, **kwargs)
        
        return wrapper
    return decorator


def require_role(role_name):
    """需要特定角色的装饰器"""
    def decorator(view_func):
        @wraps(view_func)
        def wrapper(request, *args, **kwargs):
            # 首先验证登录
            auth_header = request.META.get('HTTP_AUTHORIZATION', '')
            
            if not auth_header.startswith('Bearer '):
                return JsonResponse({'code': 401, 'info': '请先登录'}, status=401)
            
            token = auth_header.split(' ')[1]
            user = get_user_from_token(token)
            
            if not user:
                return JsonResponse({'code': 401, 'info': '登录已过期，请重新登录'}, status=401)
            
            # 检查用户状态
            if user.status != 0:
                return JsonResponse({'code': 403, 'info': '账户已被禁用'}, status=403)
            
            # 检查用户是否有指定角色
            has_role = UserRole.objects.filter(user=user, role__name=role_name).exists()
            
            if not has_role:
                return JsonResponse({'code': 403, 'info': '权限不足'}, status=403)
            
            # 将用户信息添加到request中
            request.user = user
            return view_func(request, *args, **kwargs)
        
        return wrapper
    return decorator


# 预定义的权限代码
PERMISSIONS = {
    # 用户管理权限
    'USER_VIEW': 'user:view',
    'USER_CREATE': 'user:create',
    'USER_UPDATE': 'user:update',
    'USER_DELETE': 'user:delete',
    
    # 图书管理权限
    'BOOK_VIEW': 'book:view',
    'BOOK_CREATE': 'book:create',
    'BOOK_UPDATE': 'book:update',
    'BOOK_DELETE': 'book:delete',
    
    # 借阅管理权限
    'BORROW_VIEW': 'borrow:view',
    'BORROW_CREATE': 'borrow:create',
    'BORROW_UPDATE': 'borrow:update',
    
    # 角色管理权限
    'ROLE_VIEW': 'role:view',
    'ROLE_CREATE': 'role:create',
    'ROLE_UPDATE': 'role:update',
    'ROLE_DELETE': 'role:delete',
    
    # 权限管理权限
    'PERMISSION_VIEW': 'permission:view',
    'PERMISSION_CREATE': 'permission:create',
    'PERMISSION_UPDATE': 'permission:update',
    'PERMISSION_DELETE': 'permission:delete',
}

# 预定义的角色
ROLES = {
    'ADMIN': 'admin',  # 管理员
    'LIBRARIAN': 'librarian',  # 图书管理员
    'USER': 'user',  # 普通用户
} 